<template>
  <div class="warp">
    <div class="head-box">
      <div class="head">
        <van-image width="44" height="44" round :src="userInfo.headImgUrl" />
        <div class="user">
          <div class="user-name">{{ userInfo.nikeName }}</div>
        </div>
        <div class="user-tip">
          剩余积分:
          {{ calcNum(userInfo.surplusTokens) }}
        </div>
        <div class="exchange" @click="exchangeClick">
          会员码兑换
        </div>
      </div>
    </div>
    <div class="pay-tip">如付款被提示,属于正常现象</div>
    <div class="vip-list">
      <div
        v-for="(item, index) in vipList"
        :key="index"
        class="vip-item"
        :class="{ active: currentIndex == index }"
        @click="handleCard(item, index)"
      >
        <div class="name">{{ item.cardName }}</div>
        <div class="day">{{ calcNum(item.limitCount) }}</div>
        <div class="amount">
          ¥ <span>{{ item.amount }}</span>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="pay" @click="handlePay">立即支付</div>
      <div class="bottom-tip">会员服务为虚拟商品，一经购买不可退款</div>
    </div>
    <van-popup
      v-model="exchangeShow"
      closeable
      round
      close-icon="close"
      get-container="body"
      :style="{ marginTop: isIOS ? '-140px' : '' }"
    >
      <div class="exchange-form">
        <van-cell-group>
          <van-field
            v-model="exchangeCode"
            placeholder="请输入兑换码"
            size="large"
            border
          />
        </van-cell-group>
        <div class="pay" @click="handleExchange">立即兑换</div>
      </div>
    </van-popup>
    <van-popup
      v-model="payShow"
      closeable
      round
      close-icon="close"
      get-container="body"
      :style="{ marginTop: isIOS ? '-140px' : '' }"
    >
      <div class="exchange-form">
        <div class="success" v-if="spay == 1">
          贵客来临，系统送2万积分，<br />
          请点击确认，继续使用。
        </div>
        <div class="success" v-if="spay == 2">
          重新登录成功，<br />
          请点击确认，继续使用。
        </div>
        <div class="error" v-if="spay == 3">
          积分不足， 请在本页面支付，就可使用。
        </div>
        <div class="pay" @click="closePage">确认</div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import {
  Image as VanImage,
  Col,
  Row,
  Popup,
  Field,
  CellGroup,
  Toast,
} from "vant";

import wx from "weixin-js-sdk";
export default {
  components: {
    [VanImage.name]: VanImage,
    [Col.name]: Col,
    [Row.name]: Row,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Toast.name]: Toast,
  },
  data() {
    return {
      userInfo: {},
      vipList: [],
      currentIndex: 0,
      currentInfo: {},
      exchangeShow: false,
      exchangeCode: "",
      payShow: false,
      isIOS: false,
      spay: 0,
    };
  },
  async created() {
    await this.getUserInfo();
    await this.getVipList();
  },
  mounted() {
    if (this.$route.query.spay) {
      this.payShow = true;
      this.spay = this.$route.query.spay;
    }
    if (this.judgeClient() == "IOS") {
      this.isIOS = true;
    }
  },
  methods: {
    closePage() {
      this.payShow = false;
      if (this.spay != 3) {
        wx.closeWindow();
      }
    },

    // 检查客户端
    judgeClient() {
      let u = navigator.userAgent;
      let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //判断是否是 android终端
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //判断是否是 iOS终端
      console.log("是否是Android：" + isAndroid); //true,false
      console.log("是否是iOS：" + isIOS);
      if (isAndroid) {
        return "Android";
      } else if (isIOS) {
        return "IOS";
      } else {
        return "PC";
      }
    },
    calcNum(num) {
      if (num >= 1000 && num < 10000000) {
        return num / 10000 + "w";
      } else if (num >= 10000000) {
        return num / 100000000 + "y";
      } else {
        return num;
      }
    },
    getWxPaySign(params) {
      return new Promise((resolve) => {
        // 发起请求获取签名
        {
          // 配置微信JS SDK
          wx.config({
            debug: false,
            appId: "wx1d6f991b7360ecfb",
            timestamp: params.timestamp,
            nonceStr: params.nonceStr,
            signature: params.signature,
            jsApiList: ["chooseWXPay", "chooseWXPay"],
          });
          // 配置完成后返回一个resolve
          wx.ready(() => {
            this.wxPay(params);
            resolve();
          });
        }
      });
    },

    // 发起微信支付
    wxPay(params) {
      let that = this;
      return new Promise((resolve, reject) => {
        // 调用微信支付
        wx.chooseWXPay({
          timestamp: params.timestamp,
          nonceStr: params.nonceStr,
          package: params.prepayId,
          signType: params.signType,
          paySign: params.paySign,
          success: (res) => {
            // 支付成功时返回resolve
            that.getUserInfo();
            resolve(res);
          },
          fail: (err) => {
            // 支付失败时返回reject
            reject(err);
          },
        });
      });
    },

    getUserInfo() {
      this.$axios.get(this.$urls.userInfo).then((res) => {
        const { code } = res;
        if (code == 200) {
          this.userInfo = res.result;
        }
      });
    },
    getVipList() {
      this.$axios.get(this.$urls.vipList).then((res) => {
        const { code } = res;
        if (code == 200) {
          this.vipList = res.result;
          this.currentInfo = this.vipList[0];
        }
      });
    },
    exchangeClick() {
      this.exchangeShow = true;
    },
    handleExchange() {
      if (this.exchangeCode) {
        this.$axios
          .get(this.$urls.exchangeCode + `?code=${this.exchangeCode}`)
          .then((res) => {
            const { code } = res;
            if (code == 200) {
              this.exchangeCode = "";
              this.exchangeShow = false;
              this.getUserInfo();
              Toast.success({
                message: "兑换成功",
                duration: 1.5 * 1000,
              });
            }
          });
      } else {
        Toast.fail({
          message: "请输入兑换码",
          duration: 1.5 * 1000,
        });
      }
    },
    handlePay() {
      this.$axios
        .post(this.$urls.buyMerber, {
          memberId: this.currentInfo.memberId,
          payType: 0,
        })
        .then((res) => {
          const { code } = res;
          if (code == 200) {
            this.getWxPaySign(res.result);
          }
        });
    },

    handleCard(item, index) {
      this.currentInfo = item;
      this.currentIndex = index;
    },
  },
};
</script>
<style lang="less" scoped>
.exchange-form {
  width: 300px;
  height: 120px;
  padding-top: 50px;
  margin: 0px 10px;
  .error {
    color: #f56c6c;
    text-align: center;
    font-size: 16px;
  }
  .success {
    color: #f5c379;
    text-align: center;
    font-size: 16px;
  }
  .pay {
    width: 100%;
    padding: 10px 0;
    text-align: center;
    background: linear-gradient(180deg, #fae3bf 0%, #f5c379 100%);
    border-radius: 100px;
    color: #432b0c;
    font-weight: 700;
    font-size: 16px;
    margin: 20px 0px;
  }
}
/deep/.isIOS {
  margin-top: -140px !important;
}
.warp {
  width: 100vw;
  height: 100vh;
  background: #f1f3f7;
  .head-box {
    position: relative;
    .head {
      height: 66px;
      padding: 0px 10px;
      display: flex;
      align-items: center;
      background: url("../../assets/user-bg.png") no-repeat;
      background-size: cover;
      position: relative;
      .user {
        margin-left: 10px;
        .user-name {
          max-width: 70px;
          font-weight: 600;
          font-size: 14px;
          color: #0f1113;
          margin-bottom: 2px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          -o-text-overflow: ellipsis;
        }
      }
      .user-tip {
        flex: 1;
        font-size: 14px;
        color: #8b670f;
        margin-left: 6px;
      }
      .exchange {
        padding: 6px 10px;
        background-color: #fff;
        border-radius: 4px;
        color: #4aa081;
        font-size: 11px;
        font-weight: 500;
      }
    }
  }

  .pay-tip {
    padding: 10px;
    font-size: 12px;
    color: #8b670f;
  }
  .vip-list {
    padding: 10px;
    display: flex;
    flex-direction: rows;
    .vip-item {
      width: calc(33.3% - 10px);
      height: 100px;
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
      background-color: #fff;
      margin: 0px 10px;
      display: flex;
      align-items: center;
      border-radius: 12px;
      flex-direction: column;
      box-sizing: border-box;
      .name {
        margin-top: 10px;
        color: #8b670f;
        font-size: 16px;
        font-weight: bold;
      }
      .day {
        margin-top: 8px;
        color: #8b670f;
        font-size: 12px;
      }
      .amount {
        font-size: 12px;
        color: #d4824c;
        margin-top: 8px;
        font-weight: bold;
        span {
          font-size: 16px;
        }
      }
    }
    .active {
      background-color: #f9f8df;
      border: 3px solid #e8d0a7;
    }
  }
  .footer {
    position: fixed;
    left: 0;
    right: 0;
    padding: 10px 20px 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    .pay {
      width: 100%;
      padding: 10px 0;
      text-align: center;
      background: linear-gradient(180deg, #fae3bf 0%, #f5c379 100%);
      border-radius: 100px;
      color: #432b0c;
      font-weight: 700;
      font-size: 16px;
    }
    .bottom-tip {
      text-align: center;
      margin: 5px 0 15px;
      color: #bbb;
      font-size: 12px;
    }
  }
}
</style>
